<template>
  <div>
    <ZWDrawer ref="zwRef" @submit="save" @close="close" @cancel="cancel">
      <div class="contents">

        <div class="toggleType" v-if="drawerData.controlType === 'create'">
          <div class="toggleBtn" @click="toggleType">
            <el-icon>
              <Switch />
            </el-icon>
            切换客户类型
          </div>
        </div>

        <el-form :model="form" ref="ruleFormRef" label-width="auto">

          <div class="form-title">客户信息</div>
          <el-form-item label="客户公海" required>
            <el-select v-model="form.cust_seas_id" placeholder="请选择客户公海" :disabled="drawerData.controlType == 'look'">
              <el-option v-for="(item, index) in seaids" :value="item.id" :label="item.name">{{ item.name }}</el-option>
            </el-select>
          </el-form-item>

          <el-form-item :label="item.attr_name" v-for="(item, index) in customAttr" :required="item.is_required == 2">
            <el-input v-model="item.current_val" :placeholder="'请输入' + item.attr_name" v-if="item.attr_type == 'textbox'" :disabled="drawerData.controlType == 'look'" />
            <el-input
              v-model="item.current_val"
              :placeholder="'请输入' + item.attr_name"
              show-word-limit
              maxlength="11"
              v-if="item.attr_type == 'mobile'"
              indeterminate
              @blur="valiateMobile(index, false, item.is_required)"
              :disabled="drawerData.controlType == 'look' || !!item.current_val"
            />
            <el-input :disabled="drawerData.controlType == 'look'" :show-word-limit="!!item.max_length" :maxlength="item.max_length || ''" v-if="item.attr_type == 'email'" v-model="item.current_val" :placeholder="`请输入${item.attr_name}`"></el-input>
            <el-input :disabled="drawerData.controlType == 'look'" v-model="item.current_val" v-if="item.attr_type == 'textarea'" type="textarea" :placeholder="`请输入${item.attr_name}`"></el-input>
            <el-checkbox-group v-model="item.current_val" v-if="item.attr_type == 'muti_select'" :disabled="drawerData.controlType == 'look'">
              <el-checkbox v-for="items in item.attr_val" :label="items.key">{{ items.val }}</el-checkbox>
            </el-checkbox-group>
            <el-select v-model="item.current_val" v-if="item.attr_type == 'select'" :placeholder="'请选择' + item.attr_name" :disabled="drawerData.controlType == 'look'">
              <el-option v-for="items in item.attr_val" :value="items.key" :label="items.val">{{ items.val }} </el-option>
            </el-select>

            <!-- <el-cascader style="width: 100%" :disabled="drawerData.controlType == 'look'" v-if="item.attr_type == 'pca'" v-model="item.current_val" :options="CityJson" :props="cityProps" clearable :placeholder="`请选择${item.attr_name}`" /> -->

            <el-input v-model="item.current_val" :show-word-limit="!!item.max_length" :maxlength="item.max_length || ''" :placeholder="'请输入' + item.attr_name" v-if="item.attr_type == 'pca'" :disabled="drawerData.controlType == 'look'" />

            <!-- 生日 -->
            <el-date-picker
              style="width: 100%"
              value-format="YYYY-MM-DD"
              :disabled="drawerData.controlType == 'look'"
              v-if="item.attr_type == 'date' && item.system_code == 'birthday'"
              :disabledDate="endDateOpt"
              v-model="item.current_val"
              type="date"
              :placeholder="`请输入${item.attr_name}`"
            ></el-date-picker>
            <!-- 非生日 -->
            <el-date-picker
              style="width: 100%"
              value-format="YYYY-MM-DD"
              :disabled="drawerData.controlType == 'look'"
              v-if="item.attr_type == 'date' && item.system_code != 'birthday'"
              v-model="item.current_val"
              type="date"
              :placeholder="`请输入${item.attr_name}`"
            ></el-date-picker>

            <div :class="`upload-content ${drawerData.controlType == 'look' ? 'noEdit' : ''}`" v-if="item.attr_type == 'picture'">
              <el-upload
                action="none"
                v-if="!item.current_val"
                @click="getUploadKey(index, false)"
                :on-change="beforeAvatarUpload"
                accept=".jpg,.jpeg,.png,.JPG,.JPEG,.pdf"
                :show-file-list="false"
                :limit="1"
                :auto-upload="false"
                :disabled="drawerData.controlType == 'look'"
              >
                <div class="upload-box">
                  <img src="@/assets/image/content/add-icon.png" alt="" />
                  <div>点击上传</div>
                </div>
              </el-upload>
              <div v-else-if="item.current_val.includes('.pdf')" class="upload-file-pdf">
                <div class="text">PDF</div>
                <el-icon @click="delFile(index, false)" class="del">
                  <Delete />
                </el-icon>
              </div>
              <div class="upload-file-box" v-else>
                <el-image style="width: 100%; height: 100%" :src="item.current_val" fit="cover" />
                <el-icon @click="delFile(index, false)" class="del">
                  <Delete />
                </el-icon>
              </div>
              <div class="tips"> 支持jpg、png、jpeg、pdf，大小不超过10M </div>
            </div>
          </el-form-item>

          <el-form-item label="客户阶段" required>
            <el-select v-model="form.grade_id" placeholder="请选择客户阶段" :disabled="drawerData.controlType == 'look'">
              <el-option v-for="(item, index) in levelid" :value="item.id" :label="item.name">{{ item.name }} </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="归属员工" required>
            <select-depart v-model="form.belong_work_user_id" :creators="form.belong_work_user_id_creators" :multiple="false"  :disabled="drawerData.controlType == 'look'" />
          </el-form-item>

          <!-- <el-form-item label="协助员工">
            <select-depart v-model="form.assist_ids" :creators="form.assist_ids_creators" multiple @change="changeAssist" :disabled="drawerData.controlType == 'look'" />
          </el-form-item> -->

        </el-form>
        <div class="form-title">联系人信息</div>
        <div class="contact-item" v-for="(item, index) in contactsForms">
          <div class="title">
            <span>联系人{{ index + 1 }}</span>
            <el-icon class="del" :class="{ look: drawerData.controlType == 'look' }" :size="size" :color="color" v-if="contactsForms.length > 1 && index > 0" @click="deleteContact(item, index)">
              <Delete />
            </el-icon>
          </div>
          <el-form :model="item" label-width="auto">
            <el-form-item label="姓名" required>
              <el-input v-model="item.name" :disabled="drawerData.controlType == 'look'" />
            </el-form-item>
            <el-form-item label="手机号" required>
              <el-input v-model="item.mobile" show-word-limit maxlength="11" :disabled="drawerData.controlType == 'look'" />
            </el-form-item>
          </el-form>
        </div>
        <div class="add-contact" v-if="drawerData.controlType !== 'look'" @click="addContact">添加联系人</div>
      </div>
    </ZWDrawer>

    <Dialog :appDialog="appDialogApply">
      <div class="dialog_content">该企业已存在，申请成为协助人？</div>
    </Dialog>

    <!-- <ZWDepart ref="DepartRef" @submit="getDepart" type="1" /> -->
  </div>
</template>
<script lang="ts" setup>
  import { getTaxNumber } from '@/api/common'
  import { ref, reactive, watch, onMounted, onBeforeUnmount, getCurrentInstance, ComponentInternalInstance } from 'vue'
  import { ElForm, ElMessage, ElMessageBox, UploadProps, FormRules } from 'element-plus'
  import ZWDrawer from '@/components/ZWDrawer.vue'
  import ZWDepart from '@/components/ZWDepart.vue'
  import Dialog from '@/components/Dialog.vue'

  import selectDepart from './selectDepart.vue'
  import { getClubSource } from '@/api/customer/clubManage/commonSea'
  import { stageList } from '@/view/customer/manage/configure/api'
  import { seaList, applyCompanyHelper, getPersonCustomerForm, getCompanyCustomerForm, getCompanyCustomerDetail, addCompanyCustomer, aditCompanyCustomer } from '@/api/customerCenter/customerSea'
  import { createCustomer, baseUpdate, getAttrList, customerShow } from '@/api/customerCenter'
  import { getCustomerOpenseaSelect } from '@/api/customer/manage/list'

  import { uploadFile2 } from '@/api/common'
  import { getSetionId } from '@/utils/utils'
  import { deepCopy } from '@/utils/helper'

  import CityJson from '@/assets/js/city'

  const cityProps = reactive<any>({
    value: 'name',
    label: 'name'
  })

  type FormInstance = InstanceType<typeof ElForm>
  const ruleFormRef: any = ref<FormInstance>()

  const {
    appContext: {
      config: { globalProperties }
    }
  } = <ComponentInternalInstance>getCurrentInstance()

  onMounted(() => {
    globalProperties.$bus.on('openAddCustomerCompany', () => {
      updateVisible(true)
    })
  })
  onBeforeUnmount(() => {
    globalProperties.$bus.off('openAddCustomerCompany')
  })

  type Props = {
    modelValue: boolean
    row_id: string
    sourceArr: []
  }
  const props = defineProps<Props>()
  const emit = defineEmits(['close', 'submit', 'update:modelValue'])
  const updateVisible = (flag: boolean): void => {
    emit('update:modelValue', flag)
  }

  const endDateOpt = (date: Date): boolean => {
    const now = new Date().getTime()
    return date.getTime() > now
  }

  const drawerData = ref({
    title: '添加个人客户',
    direction: 'rtl',
    userInfo: {},
    controlType: 'create',
    seas_id: ''
  })

  const cust_id = ref<any>(0)
  const cancelHandel = () => {
    appDialogApply.visible = false
  }
  const submitHandel = () => {
    applyCompanyHelper({ cust_id: cust_id.value }).then((res: any) => {
      appDialogApply.visible = false
      zwRef.value.drawer = false
      emit('submit')
    })
  }
  const appDialogApply = reactive({
    visible: false,
    title: '申请协助人',
    width: '500px',
    cancel: cancelHandel,
    submit: submitHandel,
    cancelText: '取消',
    submitText: '申请协助人'
  })

  const zwRef = ref(null)
  const DepartRef = ref(null)
  const creators = ref([])
  let form = reactive({
    cust_seas_id: '',
    grade_id: '',
    belong_work_user_id: [],
    // assist_ids: [],
    belong_work_user_id_creators: [],
    // assist_ids_creators: []
  })

  let contactsForms = reactive<any>([
    {
      name: '',
      mobile: ''
    }
  ])

  let del_contacts_info = reactive<any>([])

  const imgProps = ref([]) // 自定义图片prop

  const contactsFormRules = reactive<FormRules>({
    name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
    mobile: [{ required: true, message: '请输入手机号', trigger: 'blur' }]
  })

  // let customCropAttr = reactive<any>([])
  let customAttr = reactive<any>([])
  // 获取企业税号
  // let timer: any = null
  const taxNuIndex = ref(-1) // 是否开启企业税号
  // const onGettaxNu = (v: any, type: any) => {
  //   console.log(v, type, '企业税号')
  //   if (type == 'corp_name' && v && taxNuIndex.value != -1) {
  //     getTaxNumber({ keyword: v })
  //       .then((res: any) => {
  //         console.log('企业税号', res.credit_code)
  //         // customCropAttr[taxNuIndex.value].current_val = res.credit_code
  //         if (!res.credit_code) {
  //           ElMessage.warning('未匹配到企业')
  //         }
  //       })
  //       .catch((err: any) => {
  //         // customCropAttr[taxNuIndex.value].current_val = ''
  //       })
  //   }
  // }
  const getDetail = () => {
    if (drawerData.value.controlType === 'create') {
      getPersonCustomerForm({}).then((res: any) => {
        const { custom_attr } = res
        // customCropAttr.splice(0)
        customAttr.splice(0)
        // 是否开启企业税号
        // custom_crop_attr.forEach((item: any, index) => {
        //   if (item.system_code == 'tax_nu') {
        //     taxNuIndex.value = index
        //   }
        // })
        let ind: number = 0
        let trans = custom_attr.find((item: any, index: number) => {
          if (item.attr_name == '客户来源') {
            ind = index
            return true
          } else {
            return false
          }
        })
        if (trans) {
          let arr = props.sourceArr.map((it: any) => ({ ...it, key: it.id || '', val: it.name || '' }))
          arr.shift()
          trans.attr_val = arr
          custom_attr.splice(ind, 1, trans)
        }
        // customCropAttr.push(...custom_crop_attr)
        customAttr.push(...custom_attr)
        initSelectDefaultVal()
      })
    } else {
      getCompanyCustomerDetail({ cust_id: drawerData.value.userInfo.id }).then((res) => {
        for (let key in res) {
          if (key != 'custom_attr') {
            form[key] = res[key]
          }
        }
        // const { custom_attr, custom_crop_attr, contacts_info: contacts_info = [], belong_work_user_id: belong_work_user_id = [], assist_ids: assist_ids = [] } = res
        if (belong_work_user_id?.length) {
          form.belong_work_user_id = belong_work_user_id?.map((ite) => ite.id)
          form.belong_work_user_id_creators = belong_work_user_id
        }
        // if (assist_ids?.length) {
        //   form.assist_ids = assist_ids?.map((ite) => ite.id)
        //   form.assist_ids_creators = assist_ids
        // }
        contactsForms.splice(0)
        del_contacts_info.splice(0)
        if (contacts_info?.length) {
          if (drawerData.value.userInfo?.contact?.length) {
            const contacts = drawerData.value.userInfo.contact.map((item) => {
              return {
                id: item.id,
                name: item.name,
                mobile: item.mobile
              }
            })
            contactsForms.push(...contacts)
          }
        }
        let ind = 0
        let trans = custom_attr.find((item: any, index: number) => {
          if (item.attr_name == '客户来源') {
            ind = index
            return true
          } else {
            return false
          }
        })
        if (trans) {
          trans.current_val = Number(trans.current_val)
          let arr = props.sourceArr.map((it: any) => ({ ...it, key: it.id || '', val: it.name || '' }))
          arr.shift()
          trans.attr_val = arr
          custom_attr.splice(ind, 1, trans)
        }
        // customCropAttr.splice(0)
        customAttr.splice(0)
        // customCropAttr.push(...custom_crop_attr)
        customAttr.push(...custom_attr)
        // customCropAttr.forEach((item) => {
        //   if (item.attr_type == 'muti_select' && !item.current_val) {
        //     item.current_val = []
        //   }
        // })
        customAttr.forEach((item) => {
          if (item.attr_type == 'muti_select' && !item.current_val) {
            item.current_val = []
          }
        })
      })
    }
  }
  const seaids = reactive<any>([]) //公海列表
  const levelid = reactive<any>([]) //客户等级列表
  const sourceid = ref([]) //客户来源

  // 切换客户类型
  const toggleType = () => {
    updateVisible(false)
    globalProperties.$bus.emit('openAddCustomerSelect')
  }

  //获取客户公海列表
  const getSeaList = () => {
    seaids.splice(0)
    getCustomerOpenseaSelect({ type: 1 }).then((res: any) => {
      seaids.push(...res)
    })
  }
  //获取客户等级
  const getLevelList = () => {
    levelid.splice(0)
    stageList({ page: 1, page_size: 99 }).then((res: any) => {
      levelid.push(...res)
    })
  }
  //获取客户来源
  const getSourceList = () => {
    sourceid.value = []
    getClubSource({ page: 1, page_size: 99 }).then((res: any) => {
      res.data.forEach((item) => {
        if (item.status == 1) {
          sourceid.value.push(item)
        }
      })
    })
  }

  // const changeBelongWorkUser = (ids: any, creators: any) => {
  //   if (ids?.length && form.assist_ids?.length && form.assist_ids.includes(ids[0])) {
  //     form.belong_work_user_id = []
  //     form.belong_work_user_id_creators = []
  //     ElMessage.error('归属员工不能是协助员工')
  //   }
  // }

  // const changeAssist = (ids: any, creators: any) => {
  //   if (form.belong_work_user_id?.length && ids?.length && ids.includes(form.belong_work_user_id[0])) {
  //     const index = ids.indexOf(form.belong_work_user_id[0])
  //     let assist_ids = deepCopy(form.assist_ids)
  //     let assist_ids_creators = deepCopy(creators)
  //     form.assist_ids = []
  //     form.assist_ids_creators = []
  //     assist_ids.splice(index, 1)
  //     assist_ids_creators.splice(index, 1)
  //     form.assist_ids = assist_ids
  //     form.assist_ids_creators = assist_ids_creators
  //     ElMessage.error('归属员工不能是协助员工')
  //   }
  // }

  let nowUploadIndex = 0
  let nowUploadFlag = false
  const getUploadKey = (index: number, flag: boolean) => {
    nowUploadIndex = index
    nowUploadFlag = flag
  }

  // 上传图片的方法
  const uploadFun = (file: any, fileName: string, key: string) => {
    uploadFile2({
      file,
      fileName
    }).then((r: any) => {
      if (nowUploadFlag) {
        // customCropAttr[nowUploadIndex].current_val = r.url
        // console.log(formData.value[nowUploadKey])
        // 验证图片上传
        if (imgProps.value.length > 0) {
          imgProps.value.forEach((item) => {
            ruleFormRef.value.validateField([item])
          })
        }
      } else {
        customAttr[nowUploadIndex].current_val = r.url
        // console.log(formData.value[nowUploadKey])
        // 验证图片上传
        if (imgProps.value.length > 0) {
          imgProps.value.forEach((item) => {
            ruleFormRef.value.validateField([item])
          })
        }
      }
    })
  }
  // 上传检验
  const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile: any, key: string) => {
    if (!rawFile) {
      return
    }
    if (rawFile.size / 1024 / 1024 > 10) {
      ElMessage.error('上传图片大小不能超过10M')
      return false
    }
    uploadFun(rawFile.raw, rawFile.name, key)
  }

  //
  const delFile = (index: number, flag: boolean) => {
    if (flag) {
      // customCropAttr[index].current_val = ''
    } else {
      customAttr[index].current_val = ''
    }
  }

  const valiateMobile = (index: number, flag: boolean, required?: number) => {
    let rex = /^[1][3-9][0-9]{9}$/
    // const current_val = flag ? customCropAttr[index].current_val : customAttr[index].current_val
    if (!rex.test(current_val)) {
      ElMessage.warning('请输入合法的手机号')
      return false
    } else {
      return true
    }
  }
  const valiateid = (index: number, flag: boolean, required?: number) => {
    let rex = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{16,}$/
    // const attrs = flag ? customCropAttr[index] : customAttr[index]
    if (attrs.attr_name != '姓名' && required == 2) {
      if (!rex.test(attrs.current_val)) {
        ElMessage.warning(attrs.attr_name + '必须包含数字字母并且长度不能小于16位')
        return false
      } else {
        return true
      }
    } else {
      return true
    }
  }

  const valiateContactsForms = (): void => {
    let rex = /^[1][3-9][0-9]{9}$/
    return contactsForms.some((item) => rex.test(item.mobile))
  }

  const save = () => {
    // const validateCustomCropAttr = validateFun(customCropAttr, true)
    const validateCustomCropAttr = true
    if (validateCustomCropAttr) {
      const validateCustomAttr = validateFun(customAttr, false)
      if (validateCustomAttr && validateCustomForm()) {
        if (contactsForms.length) {
          if (contactsForms.some((item) => !item.name || !item.mobile)) {
            ElMessage.warning('请完善联系人信息')
            return
          } else if (!valiateContactsForms()) {
            ElMessage.warning('联系人手机号码有误')
            return
          }
        }
        if (drawerData.value.controlType === 'create') {
          const mobile = validateCustomAttr.find((item) => item.attr_name == '手机号')?.current_val || ''
          const corp_name = validateCustomCropAttr.find((item) => item.attr_name == '企业全称')?.current_val || ''
          const source_id = validateCustomCropAttr.find((item) => item.attr_name == '客户来源')?.current_val || ''
          const extraForm = { mobile, corp_name, source_id }
          const { belong_work_user_id: belong_work_user_id = [] } = form
          const params = { ...form, ...extraForm, belong_work_user_id: belong_work_user_id[0], custom_attr: validateCustomAttr, contacts_info: contactsForms }
          
          createCustomer(params).then((res: any) => {
            // const { is_apply, cust_id: cust_id_ } = res
            // cust_id.value = cust_id_
            // if (is_apply == 1) {            //   是否申请协助人     0 否      1 是       2 企业客户已存在，但无归属员工
            //   appDialogApply.visible = true
            // } else if(is_apply == 2){
            //   appDialogBelong.visible = true
            // }else if(is_apply == 0){
            //   ElMessage.success('保存成功')
            //   zwRef.value.drawer = false
            // }

            ElMessage.success('保存成功')
            zwRef.value.drawer = false
            emit('submit')

          })
        } else if (drawerData.value.controlType === 'edit') {
          const mobile = validateCustomAttr.find((item) => item.attr_name == '手机号')?.current_val || ''
          const corp_name = validateCustomCropAttr.find((item) => item.attr_name == '企业全称')?.current_val || ''
          const source_id = validateCustomCropAttr.find((item) => item.attr_name == '客户来源')?.current_val || ''
          const extraForm = { mobile, corp_name, source_id }
          const { belong_work_user_id: belong_work_user_id = [] } = form
          const params = { ...form, ...extraForm, belong_work_user_id: belong_work_user_id[0], custom_attr: validateCustomAttr, contacts_info: contactsForms, del_contacts_info, cust_id: drawerData.value.userInfo.id }
          baseUpdate(params).then((res) => {
            ElMessage.success('编辑成功')
            zwRef.value.drawer = false
            emit('submit')
          })
        }
      }
    }
  }

  const validateFun = (data: any, flag: boolean) => {
    if (!flag) {
    }
    try {
      data.forEach((item: any, index: number) => {
        if (!item.current_val && item.is_required == 2 && item.attr_type != 'muti_select') {
          ElMessage.warning(item.attr_name + '不能为空')
          throw new Error()
        } else if (item.attr_type == 'muti_select' && item.is_required == 2 && !item.current_val.length) {
          ElMessage.warning(item.attr_name + '不能为空')
          throw new Error()
        }
      })
    } catch (e) {
      return false
    }
    try {
      data.forEach((items: any, indexs: number) => {
        if (items.is_required == 2 && items.attr_type == 'mobile') {
          let flag2 = valiateMobile(indexs, flag)
          if (!flag2) {
            throw new Error()
          }
        } else if (items.is_required == 2 && items.attr_name != '姓名') {
          // let flag = valiateid(indexs, flag, 2)
          // if (!flag) {
          //   throw new Error()
          // }
        }
      })
    } catch (e) {
      return false
    }
    // data.forEach((item) => {
    //   delete item.attr_val
    //   delete item.is_required
    //   delete item.system_code
    // })

    return data
  }

  const validateCustomForm = (): boolean => {
    if (!form.cust_seas_id) {
      ElMessage.warning('请选择公海')
      return false
    } else if (!form.grade_id) {
      ElMessage.warning('请选择客户阶段')
      return false
    } else if (!form.belong_work_user_id.length) {
      ElMessage.warning('请选择归属员工')
      return false
    } else {
      return true
    }
  }

  const cancel = () => {
    for (let key in form) {
      if (key != 'custom_attr' && key != 'cust_seas_id') {
        form[key] = ''
      }
      initSelectDefaultVal()
    }
  }
  //数据
  const initSelectDefaultVal = () => {
    // customCropAttr.forEach((item: any) => {
    //   if (item.attr_type == 'muti_select') {
    //     item.current_val = []
    //   } else {
    //     item.current_val = ''
    //   }
    // })
    customAttr.forEach((item: any) => {
      if (item.attr_type == 'muti_select') {
        item.current_val = []
      } else {
        item.current_val = ''
      }
    })
    contactsForms.forEach((item: any) => {
      item.name = ''
      item.mobile = ''
    })
    form.belong_work_user_id = []
    // form.assist_ids = []
    form.belong_work_user_id_creators = []
    // form.assist_ids_creators = []
    form.cust_seas_id = ''
  }

  const addContact = (): void => {
    if (contactsForms.length < 5) {
      const formItem: any = {
        name: '',
        mobile: ''
      }
      contactsForms.push(formItem)
    } else {
      ElMessage.warning('最多新建5个联系人')
    }
  }

  const deleteContact = (item: any, index: number): void => {
    if (drawerData.value.controlType !== 'look') {
      if (contactsForms.length > 1) {
        ElMessageBox.confirm('确定删除该联系人吗？', '注意！', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          if (item.id) {
            del_contacts_info.push(item)
          }
          contactsForms.splice(index, 1)
        })
      }
    }
  }

  const close = () => {
    contactsForms.splice(0)
    addContact()
    emit('close')
  }
  watch(
    () => props.modelValue,
    (val) => {
      if (val) {
        form.cust_seas_id = drawerData.value.seas_id
        form.grade_id = ''
        form.belong_work_user_id = []
        // form.assist_ids = []
        form.belong_work_user_id_creators = []
        // form.assist_ids_creators = []
        zwRef.value.resetMsg = '重置'
        zwRef.value.drawerMsg = '保存'
        zwRef.value.isResetShow = true
        if (drawerData.value.controlType === 'edit') {
          zwRef.value.isResetShow = false
          zwRef.value.title = '编辑个人客户'
        } else if (drawerData.value.controlType === 'look') {
          zwRef.value.isResetShow = false
          zwRef.value.title = '查看个人客户'
        } else {
          zwRef.value.title = '添加个人客户'
        }
        getDetail()
        getSourceList()
        getLevelList()
        getSeaList()
        zwRef.value.drawer = true
        zwRef.value.width = '600px'
      } else {
        cancel()
        zwRef.value.drawer = false
      }
    }
  )

  defineExpose({
    drawerData
  })
</script>
<style scoped lang="scss">
  .contents {
    padding: 16px 0;

    .toggleType {
      margin-bottom: 6px;
      display: flex;
      justify-content: flex-end;
      align-items: center;

      .toggleBtn {
        font-size: 12px;
        color: #ff6b00;

        &:hover {
          cursor: pointer;
          color: #ffa046;
        }
      }
    }

    .form-title {
      height: 18px;
      line-height: 18px;
      font-weight: 700;
      border-left: 8px solid #ff6b00;
      padding-left: 6px;
      margin: 8px 0 24px;
    }

    .contact-item {
      border: 1px solid #eee;
      margin-bottom: 10px;
      padding: 10px 20px;
      box-sizing: border-box;

      .title {
        margin: 10px 0 16px;
        display: flex;
        justify-content: space-between;
        align-items: center;

        .del {
          color: #ff6b00;

          &:hover {
            cursor: pointer;
          }
        }
        .look {
          color: #eee;
          cursor: not-allowed;
        }
      }
    }

    .add-contact {
      display: inline-block;
      margin-top: 10px;
      margin-bottom: 20px;
      line-height: 1;
      padding: 6px 24px;
      border-radius: 4px;
      color: #ff6b00;
      border: 1px solid #ff6b00;

      &:hover {
        cursor: pointer;
        background-color: #ff6b00;
        color: #fff;
      }
    }

    .el-form {
      .el-form-item {
        .staffs_item {
          margin-right: 6px;
        }
      }

      .upload-content {
        display: flex;
        align-items: flex-end;
        .tips {
          text-indent: 6px;
          font-size: 12px;
          color: #888;
          line-height: 1.8;
        }
        &.noEdit {
          pointer-events: none !important;

          .upload-box {
            background: lightgray;
            position: relative;

            &::after {
              content: '';
              width: 100%;
              height: 100%;
              background: lightgray;
              opacity: 0.6;
              position: absolute;
              top: 0;
              left: 0;
            }
          }
        }

        .upload-box {
          width: 110px;
          height: 110px;
          text-align: center;
          border-radius: 4px;
          background: #f8f8f8;
          border: 1px solid #eaeaea;
          box-sizing: border-box;
          padding-top: 28px;

          img {
            width: 20px;
            height: 20px;
          }

          div {
            width: 100%;
            line-height: 14px;
            font-size: 14px;
            font-family: STHeitiSC-Light, STHeitiSC;
            color: #ff6b00;
          }
        }
        .upload-file-pdf {
          position: relative;
          width: 110px;
          height: 110px;
          border-radius: 4px;
          border: 1px solid #eaeaea;
          background-color: blue;
          overflow: hidden;
          .text {
            width: 110px;
            line-height: 110px;
            text-align: center;
            font-size: 18px;
            font-weight: 600;
            color: #fff;
          }
          .del {
            position: absolute;
            width: 26px;
            height: 26px;
            font-size: 18px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            background-color: #bbb;
            top: 5px;
            right: 5px;
            color: #fff;
            &:hover {
              cursor: pointer;
              background-color: #ccc;
            }
          }
        }
        .upload-file-box {
          position: relative;
          width: 110px;
          height: 110px;
          border-radius: 4px;
          border: 1px solid #eaeaea;
          overflow: hidden;
          .del {
            position: absolute;
            width: 26px;
            height: 26px;
            font-size: 18px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            background-color: #bbb;
            top: 5px;
            right: 5px;
            color: #fff;
            &:hover {
              cursor: pointer;
              background-color: #ccc;
            }
          }
        }

        .upload-desc {
          font-size: 14px;
          font-family: STHeitiSC-Light, STHeitiSC;
          font-weight: 300;
          color: #969696;
          padding-top: 10px;
          span {
            color: #ff6b00;
            cursor: pointer;
          }
        }
      }
    }
  }
</style>
